<?php
/**
 * ShopEx licence
 *
 * @copyright  Copyright (c) 2005-2010 ShopEx Technologies Inc. (http://www.shopex.cn)
 * @license  http://ecos.shopex.cn/ ShopEx License
 */
header("Content-Type: text/html;charset=utf-8"); 
//*******************************************************************
//  订单促销规则控制器
//  $ 2010-04-07 16:27 $
//*******************************************************************
class b2c_ctl_admin_sales_order extends desktop_controller{

    public $workground = 'b2c_ctl_admin_sales_coupon';

    public function index(){

        // $oGoodsPromotion = app::get("desktop")->model('tag_rel');
        // //订单促销
        // // $mOrderPromotion = $this->app->model("sales_rule_order");
        // $sql="select * from  sdb_b2c_sales_rule_order where unix_timestamp(now()) BETWEEN from_time and to_time and status =true;";

        // $promotionrefdata = $oGoodsPromotion->db->select($sql);
        // if($promotionrefdata){
        //     foreach ($promotionrefdata as $key => $value) {

        //         $aResult = unserialize($value['conditions']);
        //         var_dump($aResult['conditions'][0]['conditions'][0]['value']);
        //         var_dump(time());
        //         if($aResult['conditions'][0]['conditions'][0]['value'])
        //         {
        //             $sale_arr = array();
        //             $sale_arr[] =array(
        //                 'tag_id' => '2',
        //                 'rel_id' => $aResult['conditions'][0]['conditions'][0]['value'],
        //                 'app_id' => 'b2c',
        //                 'tag_type' => 'goods',
        //                 'last_modify' => time(),
        //                 );
        //            //sdb_desktop_tag_rel tag和对象关联表
        //             //tag_id rel_id 联合主键  不允许重复插入
        //             $repeat ="select tag_id,rel_id from sdb_desktop_tag_rel where tag_id =2 and rel_id=". $aResult['conditions'][0]['conditions'][0]['value'];
        //             if(!$oGoodsPromotion->db->select($repeat))
        //             {
        //                 try {
        //                     var_dump($sale_arr );
        //                    $res =  $oGoodsPromotion->insert($sale_arr[0]);
        //                 }
        //                 catch (Exception $e) {
        //                     $this->end(true, app::get('b2c')->_($e->getMessage()));
        //                 }
        //             }

                    

        //         }

        //     }

        // }

        $this->finder('b2c_mdl_sales_rule_order',array(
            'title'=>app::get('b2c')->_('订单促销规则'),
            'actions'=>array(
                array('label'=>app::get('b2c')->_('添加规则'),'href'=>'index.php?app=b2c&ctl=admin_sales_order&act=add','target'=>'_blank'),
                ),
            'base_filter'=>array('rule_type'=>'N')
            ));
    }

    /**
     * 添加新规则
     */
    public function add() {
        $this->pagedata['rule']['sort_order'] = 50;
        $this->_editor();
    }

    /**
     * 修改规则
     *
     * @param int $rule_id
     */
    public function edit($rule_id) {
        $mOrderPromotion = $this->app->model("sales_rule_order");
        $aRule = $mOrderPromotion->dump($rule_id,'*','default');
        //echo '<pre>';
        //var_dump($aRule);
        ///////////////////////////// 规则信息 ////////////////////////////
        //把组合的数据分割成数组
        $aRule['member_lv_ids'] = empty($aRule['member_lv_ids'])? null :explode(',',$aRule['member_lv_ids']);
        $aRule['apply_platform'] = empty($aRule['apply_platform'])? null :explode(',',$aRule['apply_platform']);

        $aRule['office_ids'] = empty($aRule['office_ids'])? null :explode(',',$aRule['office_ids']);
       //
      //$aRule['gift_numbers'] = empty($aRule['gift_numbers'])? null :explode(',',$aRule['gift_numbers']);

        $aRule['conditions'] = empty($aRule['conditions'])? null : ($aRule['conditions']);
        $aRule['action_conditions'] = empty($aRule['conditions'])? null : ($aRule['action_conditions']);
        //echo '<pre>';
        //var_dump($aRule['action_conditions']);
        $aRule['action_solutions'] = empty($aRule['action_solutions'])? null : ($aRule['action_solutions']);
        $this->pagedata['rule'] = $aRule;
         //echo '<pre>';
       // var_dump($aRule);//分割
        //echo '----sssss--';
        ///////////////////////////// 过滤条件 ////////////////////////////
        $oSOP = kernel::single('b2c_sales_order_process');
        $aHtml = $oSOP->getTemplate($aRule['c_template'],$aRule);
       // echo '<pre>';
       // var_dump($aHtml);//
        $this->_block($aHtml);//条件完成

        ///////////////////////////// 优惠方案 ////////////////////////////
        $aRule['action_solution'] = empty($aRule['action_solution'])? null : ($aRule['action_solution']);
        $oSSP = kernel::single('b2c_sales_solution_process');
        $this->pagedata['solution_type'] = $oSSP->getType($aRule['action_solution'], $aRule['s_template']);
        $html = $oSSP->getTemplate($aRule['s_template'],$aRule['action_solution'], $this->pagedata['solution_type']);
        $this->pagedata['action_solution_name'] = $aRule['s_template'];
        $this->pagedata['action_solution'] = $html;

        $this->_editor( $rule_id );
    }

    /*
        通过父地区，返回父地区名
     */
        private function _officeName($parent_aera=array(),$office_areas=array())
        {
            foreach ($parent_aera as $value) {
            //跟父级同名 或者是子地区
                if($value['local_name'] == $office_areas['local_name'] || $value['office_id'] == $office_areas['p_office_id'])
                {
                return $value['local_name'];//返回父级地区名
            }
        }
        return null;
    }

	//根据解决方案来决定前端是否需要现实赠品数量@mo
    private function _need_show_giftnumber($data = array())
    {
        //echo '<pre>';
        //var_dump($data);
      if(count($data) == 0)
         return "no";
     foreach($data as  $tem)
     {
         foreach($tem as $value)
         {
            foreach($value as $key => $value2)
            {
               if($key == "gift_promotion_solutions_gift")
                  return $key;
          }
      }
  }
  return "no";
}

    /**
     * add & edit 公共部分
     *
     */
    private function _editor( $rule_id=0 ) {
        //排斥状态显示优先级项  默认加载 addtime:14:09 2010-8-19
        $time = time();
        $filter = array('from_time|sthan'=>$time, 'to_time|bthan'=>$time, 'status'=>'true', 'rule_type'=>'N');
        if( $rule_id ) $filter['rule_id|noequal'] = $rule_id;
        $arr = $this->app->model('sales_rule_order')->getList(
            'name,sort_order',
            $filter,
            0,-1,'sort_order ASC'
            );
        $this->pagedata['sales_list'] = $arr;
        $arr = null;
        //end

		//获取该action_solution的数组@mo
        if( $rule_id ) 
        {
            $filter1['rule_id'] = $rule_id;
            $arr2 =  $this->app->model('sales_rule_order')->getList(
                'action_solution',
                $filter1,
                0,-1,'sort_order ASC'
                );
            $type_value = $this->_need_show_giftnumber($arr2); //返回数值
            $this->pagedata['action_solution_type'] = $type_value;
        }

        $this->pagedata['promotion_type'] = 'order'; // 规则类型 用于公用模板

        ////////////////////////////  模块  ////////////////////////////////
        $this->pagedata['sections'] = $this->_sections();
        //按数据库的默认字段来取出来

        //下面是重新覆盖相关的值
        //
        //////////////////////////// 会员等级 //////////////////////////////
        $mMemberLevel = $this->app->model('member_lv');
        $this->pagedata['member_level'] = $mMemberLevel->getList('member_lv_id,name', array(), 0, -1, 'member_lv_id ASC');

        //////////////////////////// 办事处 //////////////////////////////
        ///
        ///@mo


       //add by peter 2017-03-23 增加办事处选择
        $office=app::get('ectools')->model('office')->getList('*',array('disabled'=>'false'),0,-1,'ordernum ASC,office_id ASC');
        $this->pagedata['office']=$office;      
        $model=app::get('ectools')->model('office');
        $officeToplevel=$model->db->select('select * from '.$model->table_name(1).' where disabled="false" and p_office_id is null order by ordernum ASC, office_id ASC');

        $html4 = $this->procOfficeHTML($officeToplevel,$rule_id);
       //$this->pagedata['menus4']="<ul><li><input class='parent' type=\"checkbox\">全选<ul>"."</ul></li></ul>";
        $this->pagedata['menus4']="<ul><li><input id=\"showoffice\" class='' type=\"checkbox\" checked=\"checked\">显示/隐藏<ul><span id=\"stpl_list1\">".$html4."</span></ul></li></ul>";

       //////////////////////////////////////////

        //////////////////////////// 过滤条件模板 //////////////////////////////
        $oSOP = kernel::single('b2c_sales_order_process');

        // echo "<pre>";
        // var_dump( $oSOP->getTemplateList() );
        // exit();

        $this->pagedata['pt_list'] = $oSOP->getTemplateList();//目前查到只有订单，没有指定商品的

       // echo '<pre>';
        //var_dump($this->pagedata['pt_list']);//数组，所有优惠策略的信息

        //////////////////////////// 优惠方案模板 //////////////////////////////
        $oSSP = kernel::single('b2c_sales_solution_process');

        // echo "<pre>";
        // var_dump( $oSSP->getTemplateList() );
        // exit();

        $this->pagedata['stpl_list'] = $oSSP->getTemplateList();

        //add by lkb 2017-05-26 去掉优惠方案下的：1、订单以固定折扣出售(首批打折) 2、订单送赠品(满赠促销)
        unset($this->pagedata['stpl_list']['order']['b2c_promotion_solutions_topercent2']);
        unset($this->pagedata['stpl_list']['order']['gift_promotion_solutions_gift']);
        //add end 

        header("Cache-Control:no-store");
        $this->singlepage('admin/sales/promotion/frame.html');
    }

////////////////
//add by peter 2017-03-23 循环拼接办事处checkbox树形样式
    function procOfficeHTML($tree,$rule_id=-1){
        $html = '';
        foreach($tree as $k=>$t){
            if($t['p_office_id']==null){
                $html.="<ul><li style='padding-left:25px;text-align:left;'><input class='parent leaf' type='checkbox' value=''>".$t['local_name'];
                $childOffice=app::get('ectools')->model('office')->getList('*',array('p_office_id'=>$t['office_id'],'disabled'=>'false'),0,-1,'ordernum ASC,office_id ASC');
                $html.="<ul>".$this->procOfficeHTML($childOffice,$rule_id)."</ul></li></ul>";
            }
            else{
                $childOffice=app::get('ectools')->model('office')->getList('*',array('p_office_id'=>$t['office_id'],'disabled'=>'false'),0,-1,'ordernum ASC,office_id ASC');
                if ($childOffice==null){
                        //add by peter 2017-03-24 判断是否选择

                    $checked='';
                    if ($rule_id!=0){
                        $this_rule_offices =app::get('b2c')->model('sales_rule_order')->getList('office_ids',array('rule_id'=>$rule_id),0,-1,'rule_id ASC');

                        $office_array = explode(',',$this_rule_offices[0]['office_ids']);    
                        if(in_array($t['office_id'],$office_array))
                            $checked = "checked='checked'";
                    }   
                    $html .= "<li style='padding-left:25px;text-align:left;'><input class='leaf' type='checkbox' ".$checked." name='rule[office_ids][]' value=".$t['office_id'].">{$t['local_name']}</li>";
                }else{
                    $html.= "<ul><li style='padding-left:25px;text-align:left;'><input  class='parent leaf'  type='checkbox' value=''>".$t['local_name'];
                    $html.="<ul>".$this->procOfficeHTML($childOffice,$rule_id)."</ul></li></ul>"; 
                }
            } 
        }
        return $html;
    }
/////////

    private function _sections() {
     return  array(
       'basic'=> array(
           'label'=>app::get('b2c')->_('基本信息'),
           'options'=>'',
           'file'=>'admin/sales/promotion/basic.html',
                           ), // basic
       'conditions'=> array(

        'label'=>app::get('b2c')->_('优惠条件'),

        'options'=>'',
        'file'=>'admin/sales/promotion/conditions.html',
                              ), // conditions
       'solution'=> array(
          'label'=>app::get('b2c')->_('优惠方案'),
          'options'=>'',
          'file'=>'admin/sales/promotion/solution.html',
                            ), // solutions
       );
 }
    //提交后
 public function toAdd() {

    $this->begin();
    $aData = $this->_prepareRuleData($_POST);

        //echo "<pre>";//have output submit data
        //var_dump($aData);
        //exit;

    if (isset($aData['conditions']['conditions'][0]['value']) && $aData['conditions']['conditions'][0]['value']){
        if(floatval($aData['conditions']['conditions'][0]['value']) <= 0){
            $this->end( false,'请输入正数！'  );
        }
    }
    if (isset($aData['action_solution']['b2c_promotion_solutions_byfixed']['total_amount']) && $aData['action_solution']['b2c_promotion_solutions_byfixed']['total_amount']){
        if(floatval($aData['action_solution']['b2c_promotion_solutions_byfixed']['total_amount']) <= 0){
            $this->end( false,'请输入正数！'  );
        }
    }

        //add by lkb 商品多选修改，限制为单选
    if($aData['action_conditions']['conditions']&&$aData['conditions']['conditions'][0]['conditions'][0]['value'])
    {
       $aData['action_conditions']["conditions"][0]["value"]=array('0' =>$aData['conditions']['conditions'][0]['conditions'][0]['value'] );
   }

        //add end   


   if ($aData['member_lv_ids'] == null ){
    $this->end(false, '请选择会员等级');
}
        // if ($aData['office_ids'] == null ){
        //     $this->end(false, '请选择办事处');
        // }
if ($aData['apply_platform'] == null ){
    $this->end(false, '请选择活动平台');
}

$mSRO = $this->app->model("sales_rule_order");
$bResult = $mSRO->save($aData);

$this->end($bResult,app::get('b2c')->_('操作成功'));
}

    /**
     * 这个MS可以放入model里处理
     */
    private function _prepareRuleData($aData) {
        ///////////////////////////// 基本信息 //////////////////////////////////
        $aResult = $aData['rule'];

        if( !$aResult['name'] ) $this->end( false,'促销名称不能为空！' );

        // 开始时间&结束时间
        foreach ($aData['_DTIME_'] as $val) {
            $temp['from_time'][] = $val['from_time'];
            $temp['to_time'][] = $val['to_time'];
        }
        $aResult['from_time'] = strtotime($aData['from_time'].' '. implode(':', $temp['from_time']));
        $aResult['to_time'] = strtotime($aData['to_time'].' '. implode(':', $temp['to_time']));
        if( $aResult['to_time']<=$aResult['from_time'] ) $this->end( false,'结束时间不能小于开始时间！' );

        // 会员等级
        $aResult['member_lv_ids'] = empty($aResult['member_lv_ids'])? null : implode(',',$aResult['member_lv_ids']);

        //办事处
        $aResult['office_ids'] = empty($aResult['office_ids'])? null : implode(',',$aResult['office_ids']);
        
        //赠品数量
       // $aResult['gift_numbers'] = empty($aResult['gift_numbers'])? null : implode(',',$aResult['gift_numbers']);
        // 活动平台
        $aResult['apply_platform'] = empty($aResult['apply_platform'])? null : implode(',',$aResult['apply_platform']);

        // 创建时间 (修改时不处理)
        if(empty($aResult['rule_id'])) $aResult['create_time'] = time();

        ////////////////////////////// 过滤规则 //////////////////////////////////
        $aResult['conditions'] = empty($aData['conditions'])? ( array('type'=>'combine','conditions'=>array())) : ($aData['conditions']);
        //if(is_null($aResult['conditions'])) $aResult['c_template'] = null;
        $aResult['action_conditions'] = empty($aData['action_conditions'])? ( array('type'=>'product_combine','conditions'=>array())) : ($aData['action_conditions']);

        ////////////////////////////// 优惠方案 //////////////////////////////////
        if ($aData['action_solution']['progetcoupon_promotion_solutions_getcoupon']['cpns_id']){
            if (!is_array($aData['action_solution']['progetcoupon_promotion_solutions_getcoupon']['cpns_id'])){
                $this->end( false,'请选择至少一张优惠券' );
                $aData['action_solution']['progetcoupon_promotion_solutions_getcoupon']['cpns_id'] = null;
            }
        }
        $aResult['action_solution'] = empty($aData['action_solution'])? null : ($aData['action_solution']);
        if( empty($aResult['sort_order']) && $aResult['sort_order']!==0 )
            $aResult['sort_order'] = 50;

        if( $aResult['sort_order'] ) $aResult['sort_order'] = (int)$aResult['sort_order'];

        /**
         * 校验删选相应的表单元素
         */
        if(is_null($aData['rule']['c_template'])){
          $this->end(false,'优惠条件必选一项');
      }

      if(is_null($aData['rule']['s_template'])){
        $this->end(false,'优惠方案必选一项');
    }

    $obj_rule_c_template = kernel::single($aData['rule']['c_template']);
    if ($obj_rule_c_template){
        if (method_exists($obj_rule_c_template, 'verify_form'))
            if (!$obj_rule_c_template->verify_form($aData,$msg)){
                $this->end( false, $msg);
            }
        }

        $obj_rule_s_template = kernel::single($aData['rule']['s_template']);
        if ($obj_rule_s_template){
            if (method_exists($obj_rule_s_template, 'verify_form'))
                if (!$obj_rule_s_template->verify_form($aData,$msg)){
                    $this->end( false, $msg);
                }
            }

            if($aResult['c_template'] == "proqgoods_conditions_goods_goodsofquantity" && (strpos($aResult['conditions']['conditions'][0]['value'],".") || strpos($aResult['conditions']['conditions'][0]['value'],".") === 0)){
                $goods_id = $aResult['conditions']['conditions'][0]['conditions'][0]['value'];
                $goodsinfo = $this->app->model('goods')->getList('type_id',array('goods_id'=>$aResult['conditions']['conditions'][0]['conditions'][0]['value']));
                $typeinfo = $this->app->model('goods_type')->getList('floatstore',array('type_id'=>$goodsinfo[0]['type_id']));
                if(!$typeinfo[0]['floatstore'])
                    $aResult['conditions']['conditions'][0]['value'] = floor($aResult['conditions']['conditions'][0]['value']);
            }
            return $aResult;
        }

        private function _block($aHtml) {
            if((empty($aHtml)) || ( is_array($aHtml) && (empty($aHtml['conditions']) || empty($aHtml['action_conditions']))) ) die("<b align=\"center\">".app::get('b2c')->_("模板生成失败")."</b>");
            if(is_array($aHtml)) {
                $this->pagedata['conditions'] = $aHtml['conditions'];
                $this->pagedata['action_conditions'] = $aHtml['action_conditions'];
                $this->pagedata['multi_conditions'] = true;
            } else {
                $this->pagedata['multi_conditions'] = false;
                $this->pagedata['conditions'] = $aHtml;
            }
        }

    /**
     * 获取指定模板
     */
    public function template(){
        $oSOP = kernel::single('b2c_sales_order_process');
        // 只载入模板 有值的话也是没什么用的
        $aHtml = $oSOP->getTemplate($_POST['template']);

        $this->_block($aHtml);
        $this->display('admin/sales/promotion/order_rule.html');
    }



    /**
     * 用于优惠方案获取模板
     */
    public function solution() {
        $oSSP = kernel::single('b2c_sales_solution_process');
        // 只载入模板 这里只是选择模板
        $html = $oSSP->getTemplate($_POST['template'], array(), $_POST['type']);
        if(empty($html)) die("<b align=\"center\">".app::get('b2c')->_("模板生成失败")."</b>");

        $this->pagedata['conditions'] = $html;
        $this->display('admin/sales/promotion/goods_rule.html');
    }



    /**
     * 选择条件
     *
     */
    public function conditions(){
        // 传入的值为空的处理
        if(empty($_POST)) exit;

        // vpath
        $_POST['path'] .= '[conditions]['.$_POST['position'].']';
        $_POST['level'] += 1;

        $oSOP = kernel::single('b2c_sales_order_process');
        echo $oSOP->makeCondition($_POST);
    }
}
